package cn.gjxblog.core.captcha;

import cn.gjxblog.core.captcha.img.ImgCaptcha;
import cn.gjxblog.core.captcha.sms.SmsCapthcha;
import cn.gjxblog.core.captcha.sms.SmsSender;
import cn.gjxblog.core.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/1/16 14:14
 */
@RestController
public class CaptchaController {

    public static final String ssession_key ="CAPTCHA_CODE";

    @Resource
    private SecurityProperties securityProperties;

    @Resource
    private SmsSender smsSender;

    @Autowired
    private CaptchaGenerator imgCaptchaGenerator;

    @Autowired
    private CaptchaGenerator smsCaptchaGenerator;

    @RequestMapping("/captcha/img")
    public void getCaptcha(HttpSession httpSession, HttpServletResponse response) throws IOException {
            //1.创建验证码
        ImgCaptcha captcha = (ImgCaptcha) imgCaptchaGenerator.createCaptcha();

        //2. 将验证码写入session中
        httpSession.setAttribute(ssession_key,captcha);
            //3. 响应图片
        ImageIO.write(captcha.getImage(),"PNG",response.getOutputStream());
    }

    @RequestMapping("/captcha/sms")
    public void getSmsCaptcha(HttpSession httpSession, HttpServletRequest request) throws IOException {
        //1.创建验证码
        SmsCapthcha captcha = (SmsCapthcha) smsCaptchaGenerator.createCaptcha();
        //2. 将验证码写入session中
        httpSession.setAttribute(ssession_key,captcha);
        //3. 发送验证码
        String mobile = request.getParameter("mobile");
        smsSender.send(captcha.getCode(),mobile);

    }


}
